class Stock < ApplicationRecord
  has_many :block_stocks, dependent: :delete_all
  has_many :blocks, through: :block_stocks

  scope :is_held?, -> { where(is_held: true) }
  scope :is_choice?, -> { where(is_choice: true) }
  scope :is_alert?, -> { where(is_alert: true) }
  scope :is_long?, -> { where(is_long: true) }
  scope :is_buy_point?, -> { where(is_buy_point: true) }

  before_save :clear_note_if_alert_false, :auto_choice_at
  def clear_note_if_alert_false
    self.note = nil if !self.is_alert && self.note.present?
  end

  def auto_choice_at
    if self.is_choice && self.choice_at.nil?
      self.choice_at = Time.now
    elsif !self.is_choice && self.choice_at.present?
      self.choice_at = nil
    end
  end

  def self.ransackable_attributes(auth_object = nil)
    ["act_ent_type", "act_name", "area", "buy_price", "sell_price", "cnspell", "created_at", "id", "id_value", "industry", "is_black", "is_choice", "is_alert", "list_date", "market", "name", "symbol", "ts_code", "updated_at", "ma_alert", "note"]
  end
end
